﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.Windows.Forms;
using System.IO;
using DevExpress.XtraEditors; 

namespace TaxiDispatchClient
{
    public partial class ImageForm : DevExpress.XtraEditors.XtraForm
    {
        public ImageForm()
        {
            InitializeComponent(); 
           
        }
        private string _currentPath = ""; //当前路径
        private string[] _sources; //复制文件的源路径
        private bool _ismove;
        private readonly string _imageFloderPath = Application.StartupPath + @"\taxiimages\";  //  图片存放路径
        private string _taxino = "";

        private void ImageForm_Load(object sender, EventArgs e)
        {
            ListFolders();

        }

        private void ListFolders()
        {
            
            if(!Directory.Exists(_imageFloderPath))
            {
                Directory.CreateDirectory(_imageFloderPath);
            }
            DirectoryInfo mainFolderPath = new DirectoryInfo(_imageFloderPath);
            DirectoryInfo[] folderList = mainFolderPath.GetDirectories("*");
            List<string>  monthlist = new List<string>() ;
            foreach (DirectoryInfo folder in folderList)
            {
               string folermonth = folder.Name.Remove(folder.Name.LastIndexOf('-'));
               folermonth = folermonth + "月";
               if (! monthlist.Contains(folermonth))
               {
                   monthlist.Add(folermonth);
                   TreeNode nodeMonth = treeView1.Nodes.Add(folermonth);
                   nodeMonth.Name = folermonth;
                   nodeMonth.ImageIndex = 0;
                   nodeMonth.SelectedImageIndex = 0;
                   //nodeMonth.NodeFont = new Font("宋体", 14);
               }

               TreeNode nodeDay = treeView1.Nodes[folermonth];
               nodeDay.Nodes.Add(folder.Name);
               nodeDay.ImageIndex = 0;
               nodeDay.SelectedImageIndex = 0;
                
            }
            //foreach (TreeNode node in treeView1.Nodes)
            //{
            //    NodeUpdate(node);
            //}
        }   

        //更新结点(列出当前目录下的子目录)
        //private void NodeUpdate(TreeNode node)
        //{
        //    try
        //    {
        //        node.Nodes.Clear();
        //        DirectoryInfo dir = new DirectoryInfo(node.FullPath);
        //        DirectoryInfo[] dirs = dir.GetDirectories();
        //        foreach (DirectoryInfo d in dirs)
        //        {
        //            node.Nodes.Add(d.Name);
        //        }
        //    }
        //    catch
        //    {
        //    }
        //}
    
        //更新列表(列出当前目录下的目录和文件)
        private void ListUpdate(string newPath)
        {
            if (newPath == "")
                ListFolders();
            else
            {  
                try
                {
                    DirectoryInfo currentDir = new DirectoryInfo(newPath);
                    DirectoryInfo[] dirs = currentDir.GetDirectories(); //获取目录
                    FileInfo[] files = currentDir.GetFiles();   //获取文件
                    if( _taxino !="")                             
                    {
                        files = currentDir.GetFiles(_taxino+"*");   //获取指定出租车的文件
                    }
                        //列出文件夹
                    foreach (DirectoryInfo dir in dirs)
                    {
                        ListViewItem dirItem = listView1.Items.Add(dir.Name, 2);
                        dirItem.Name = dir.FullName;
                        dirItem.SubItems.Add("");
                        dirItem.SubItems.Add("文件夹");
                        dirItem.SubItems.Add(dir.LastWriteTimeUtc.ToString());
                    }

                    listView1.LargeImageList = imageList2;
                    imageList2.ImageSize = new Size(120, 120);
                    imageList2.ColorDepth = ColorDepth.Depth32Bit; 
                    //列出文件
                    foreach (FileInfo file in files)
                    {
                        ListViewItem fileitem = new ListViewItem();
                        if (file.Extension == ".jpg" || file.Extension == ".png" ||
                            file.Extension == ".gif" || file.Extension == ".bmp")   //扩展名为图片
                        {   

                            fileitem.Name = file.FullName;
                            fileitem.Text = file.Name;
                            listView1.Items.Add(fileitem);
                            imageList2.Images.Add(Image.FromFile(file.FullName));
                            
                        }
                        //else    //其它文件
                        //{
                            
                        //}
                    }
                    for (int i = 0; i < listView1.Items.Count;i++ )
                    {
                        listView1.Items[i].ImageIndex = i;
                    }
                    _currentPath = newPath;
                    textEdit_address.Text = _currentPath;
                    label_total.Text=listView1.Items.Count + "张";     //更新状态栏
                }
                catch (Exception ex)
                {
 
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            listView1.Items.Clear();
            imageList2.Images.Clear();
            e.Node.Expand();
            if (!e.Node.Text.ToString().Contains('月'))
            {
                ListUpdate(_imageFloderPath + e.Node.Text + "\\");
            }
        }

      


      
        private void Delete()
        {
            if (listView1.SelectedItems.Count == 0)
                return;
            if (XtraMessageBox.Show("确认删除该图片？", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    foreach (ListViewItem item in listView1.SelectedItems)
                    {
                        string path = item.Name;
                        if (File.Exists(path))  //文件
                            File.Delete(path);
                        else if (Directory.Exists(path))    //目录
                            Directory.Delete(path, true);
                        listView1.Items.Remove(item);
                    }
                    label_Status.Caption = "共有  " + listView1.Items.Count + "张 图片";
                }
                catch (Exception ex)
                {

                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }
            }
        }


        //得到复制文件列表
        private void Copy()
        {
            if (listView1.SelectedItems.Count == 0)
                return;
            int count = listView1.SelectedItems.Count;
            _sources = new String[count];
            int i = 0;
            foreach (ListViewItem item in listView1.SelectedItems)
            {
                _sources[i++] = item.Name;
            }
            _ismove = false;
        }

        //剪切
        //private void Cut()
        //{
        //    Copy();
        //    _ismove = true;
        //}

        //复制文件
        //private void CopyFile(string source)
        //{
        //    try
        //    {
        //        FileInfo file = new FileInfo(source);
        //        string destination = Path.Combine(_currentPath, file.Name);
        //        if (destination == source)  //目标路径和源路径相同，返回
        //            return;
        //        if (_ismove) //移动
        //            file.MoveTo(destination);
        //        else    //复制
        //            file.CopyTo(destination);
        //        //listView1.Items.Add(file.Name);
        //    }
        //    catch (Exception ex)
        //    {
        //        Common.CommonRoutine.HandlingExceptions(ex, true);
        //        return;
        //    }

        //}
        public static void CopyToClipboard(string[] files, bool cut)
        {
            if (files == null) return;
            IDataObject data = new DataObject(DataFormats.FileDrop, files);
            MemoryStream memo = new MemoryStream(4);
            byte[] bytes = new byte[] { (byte)(cut ? 2 : 5), 0, 0, 0 };
            memo.Write(bytes, 0, bytes.Length);
            data.SetData("Preferred DropEffect", memo);
            Clipboard.SetDataObject(data);
        }

        /// <summary>
        /// 获取剪贴板中的文件列表（方法）
        /// </summary>
        /// <returns>System.Collections.List<string>返回剪切板中文件路径集合</returns>
        //public static List<string> GetClipboardList()
        //{
        //    List<string> clipboardList = new List<string>();
        //    System.Collections.Specialized.StringCollection sc = Clipboard.GetFileDropList();
        //    for (int i = 0; i < sc.Count; i++)
        //    {
        //        string listfileName = sc[i];
        //        clipboardList.Add(listfileName);
        //    }
        //    return clipboardList;
        //}
 


        //粘贴
        //private void Paste()
        //{
          
        //    List<string>  pathlist = GetClipboardList();
        //    if(pathlist ==null)
        //        return;
        //    foreach(string  strpath in pathlist)
        //    {
        //        if(File.Exists(strpath))
        //        {
        //            CopyFile(strpath);
        //        }
        //    }
        //    listView1.Items.Clear();
        //    imageList2.Images.Clear();
        //    ListUpdate(_currentPath);
        //    _sources = new string[10];
        //}
     

        private void barButtonItem_copy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Copy();
            CopyToClipboard(_sources,_ismove);
        }

        //private void barButtonItem_paste_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    Paste();
        //}
        private void barButtonItem_delete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Delete();

        }

        private void listView1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point p = new Point(Cursor.Position.X, Cursor.Position.Y);
                popupMenu1.ShowPopup(p);
                barButtonItem_copy.Enabled = listView1.SelectedItems.Count != 0;
                //barButtonItem_paste.Enabled = GetClipboardList().Count > 0;
                barButtonItem_delete.Enabled = listView1.SelectedItems.Count != 0;
                barButtonItem_detail.Enabled = listView1.SelectedItems.Count != 0;


            }
        }

        private void barButtonItem_refresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            listView1.Items.Clear();
            imageList2.Images.Clear();
            ListUpdate(_currentPath);
            Refresh();
        }



        private List<string> GetFilelist(string taxino)
        {
            List<string> filelist = new List<string>();
            string Path = Application.StartupPath + @"\taxiimages\";  //  图片存放路径
            DirectoryInfo currentDir = new DirectoryInfo(Path);
            DirectoryInfo[] dirs = currentDir.GetDirectories(); //获取目录  
            //列出文件
            foreach (DirectoryInfo dir in dirs)
            {
                FileInfo[] files = dir.GetFiles(taxino + "*");
                //int i = filelist.Count();
                foreach (FileInfo file in files)
                {
                    filelist.Add(file.FullName);
                }

            }
            return filelist;
        }
        private void ListFolder_taxino(List<string> filelist)  //列出选择的司机上传过图片的日期
        {
            if (filelist == null)
                return;
            List<string> monthlist = new List<string>();
            List<string> datelist = new List<string>();
            foreach (string file in filelist)
            {
                string month = file.Substring(file.IndexOf('_') + 1, 6).Insert(4, "年");
                month = month + "月";
                if (!monthlist.Contains(month))
                {
                    monthlist.Add(month);
                    TreeNode nodeMonth = treeView1.Nodes.Add(month);
                    nodeMonth.Name = month;
                    nodeMonth.ImageIndex = 0;
                    // nodeMonth.SelectedImageIndex = 0;
                }
                TreeNode nodeDay = treeView1.Nodes[month];
                string date = file.Remove(file.LastIndexOf("\\"));
                date = date.Remove(0, date.LastIndexOf("\\") + 1);
               
                if (!datelist.Contains(date))
                {
                    datelist.Add(date);
                    nodeDay.Nodes.Add(date);
                    nodeDay.ImageIndex = 0;
                    nodeDay.SelectedImageIndex = 0;
                }
            }
        
        }
        private void buttonEdit_driver_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DriverInfoForm driverInfoForm = new DriverInfoForm();
            driverInfoForm.ShowDialog();
            if (driverInfoForm.gridView1.FocusedRowHandle >= 0)
            {
                DataRow row = driverInfoForm.gridView1.GetDataRow(driverInfoForm.gridView1.FocusedRowHandle);
                buttonEdit_driver.Text = row["taxino"].ToString();
                label_driver.Text = row["Name"].ToString();
                label_workid.Text = row["WorkId"].ToString();
                try
                {
                    treeView1.Nodes.Clear();
                    listView1.Items.Clear();
                    imageList2.Images.Clear();
                    _taxino = buttonEdit_driver.Text;
                    List<string> filelist = GetFilelist(_taxino);
                    ListFolder_taxino(filelist);
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }

            }
        }
         
        private void barButtonItem_detail_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (listView1.SelectedItems.Count == 0) //无对象选中时，显示当前文件夹属性
            {
                return;
            }
            else    //有对象选中时 
            {
                 
                ImageInfoForm imginfform = new ImageInfoForm(this);
                imginfform.ShowDialog();
              
            }
        }

        private void listView1_ItemActivate(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                //string newPath = listView1.SelectedItems[0].Name;
                try
                {
                    ImageInfoForm imginfform = new ImageInfoForm(this);
                    imginfform.ShowDialog();
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }
            }
        }

        private void barButtonItem_allselect_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (listView1.Items.Count <= 0) return;
            for(int i = 0 ; i<listView1.Items.Count;i++)
            {
                listView1.Items[i].Selected = true;
            }
        }

        private void radioGroup_type_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(radioGroup_type.SelectedIndex==0)
            {
                panelControl_driver.Visible = false;
                treeView1.Location = panelControl_driver.Location;
                treeView1.Size = new Size(treeView1.Width,treeView1.Height+panelControl_driver.Height);
                treeView1.Nodes.Clear();
                listView1.Items.Clear();
                _taxino = "";
                ListFolders();
                label_total.Text = "0张";
            }
            else
            {
                panelControl_driver.Visible = true;
                buttonEdit_driver.Text = "";
                treeView1.Location = new Point(treeView1.Location.X,panelControl_driver.Location.Y+panelControl_driver.Height);
                treeView1.Size = new Size(treeView1.Width,treeView1.Height-panelControl_driver.Height);
                treeView1.Nodes.Clear();
                listView1.Items.Clear();
                label_total.Text = "0张"; 
            }
        }
        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
    }
}